﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2009, 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */


using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

using Twipler.App.DataDoc;
using Twipler.WebApp;

namespace Twipler.App.Render.Tree
{
    public abstract class LinkBuilderQueryString
    {
        public string Name;

        public abstract void Render(StringBuilder html);

        public static LinkBuilderQueryString Deserialize(string decode)
        {
            string[] parts = decode.Split(',');

            if (string.Equals(parts[0], "int", StringComparison.OrdinalIgnoreCase))
                return LinkBuilderQueryStringInt.Decode(parts);

            return null;
        }
    }

    public class LinkBuilderQueryStringInt : LinkBuilderQueryString
    {        
        public int Default;
        public int Delta;
        public int Min;
        public int Max;

        public override void Render(StringBuilder html)
        {
            int i;
            if (!int.TryParse(HttpContext.Current.Request.QueryString[Name], out i))
                i = Default;

            i += Delta;

            if (i > Max)
                i = Max;

            if (i < Min)
                i = Min;

            html.AppendFormat("{0}={1}&", Name, i);
        }

        public static LinkBuilderQueryStringInt Decode(string[] parts)
        {
            if (parts.Length != 6)
                return null;

            LinkBuilderQueryStringInt obj = new LinkBuilderQueryStringInt();

            obj.Name = parts[1];

            if (!int.TryParse(parts[2], out obj.Default))
                return null;

            if (!int.TryParse(parts[3], out obj.Delta))
                return null;

            if (!int.TryParse(parts[4], out obj.Min))
                return null;

            if (!int.TryParse(parts[5], out obj.Max))
                return null;

            return obj;
        }
    }

    public enum LinkBuilderQueryStringMode { New, Update }

    public class LinkBuilderItem : AbstractItem
    {
        private string _page;
        private List<LinkBuilderQueryString> _queryString;
        private LinkBuilderQueryStringMode _mode = LinkBuilderQueryStringMode.New;
       
        public override List<AbstractItem> Children { get { return null; } }

        public static LinkBuilderItem Create(string page, List<LinkBuilderQueryString> queryString, LinkBuilderQueryStringMode mode)
        {
            return new LinkBuilderItem() { _page = page, _queryString = queryString, _mode = mode };
        }

        public override void Render(System.Text.StringBuilder html, App.Machine.Environment environment)
        {
            switch (_page)
            {
                case null:
                case "":
                    html.AppendFormat("{0}.html", Current.PageProducer.Name);
                    break;

                case "style":
                    html.AppendFormat(Current.StylesheetProducer.HttpPath);
                    break;

                case "selectstyle":
                    html.AppendFormat(QueryStringHash.Protect("/settings/theme/selectstyle.aspx?designid=" + Current.Visitor.Design.Id));
                    break;

                default:
                    html.Append(_page);
                    break;
            }



            if (IsQueryStringEmpty())
            {
                
                if (_mode == LinkBuilderQueryStringMode.Update)
                {
                    if (HttpContext.Current.Request.RawUrl.IndexOf("?") != -1)
                        html.Append(HttpContext.Current.Request.RawUrl.Substring(HttpContext.Current.Request.RawUrl.IndexOf("?")));
                }

                //if (_mode == LinkBuilderQueryStringMode.New)
                //  return;

                return;
            }


            // Output the new query string section.
            html.Append("?");

            foreach (LinkBuilderQueryString qs in _queryString)
                qs.Render(html);

            // If 'update' then output any undefined query string parts
            if (_mode == LinkBuilderQueryStringMode.Update)
            {
                foreach (string item in HttpContext.Current.Request.QueryString)
                {
                    if (_queryString.Exists(qs => String.Equals(qs.Name, item, StringComparison.OrdinalIgnoreCase)))
                        continue;
                    
                    html.AppendFormat("{0}={1}&", item, HttpContext.Current.Request.QueryString[item]);
                }
            }

            html.Remove(html.Length - 1, 1);            
        }

        private bool IsQueryStringEmpty()
        {
            return (_queryString == null) || (_queryString.Count == 0);
        }
    }
}
